package com.hoshiicloud.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.payment.Payment;
import com.hoshiicloud.payment.Platform;
import com.hoshiicloud.payment.feign.IdGeneratorService;
import com.hoshiicloud.payment.feign.UserFeignService;
import com.hoshiicloud.payment.feign.UploadService;
import com.hoshiicloud.payment.mapper.PaymentMapper;
import com.hoshiicloud.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 支付方式配置信息 服务实现类
 * </p>
 *
 * @author Mr.wu
 * @since 2019-05-13
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements
        PaymentService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private UserFeignService platformService;

    /**
     * @param entity
     * @param file
     * @return boolean
     * @author: Mr.wu
     * @descripton: 新增支付配置和支付证书
     * @date: 10:12 2019/6/10
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payment", allEntries = true)
    @Logable(authName = "支付服务-支付方式配置信息-新增支付方式配置信息并上传证书")
    @Override
    public Response saveByCert(Payment entity, MultipartFile file) {
        //验证平台属性
        Response result = platformService.getById(entity.getPlatformId());
        if (!result.isSuccess() || result.getData() == null) {
            return Response.failed("校验平台信息失败");
        }
        Platform platform = (Platform) result.getData();
        //TODO 根据租户或平台获得存储空间名称
        String bucketName = "obs-7d37";
        String objectKey = "";
        String fileName = "";
        String folder = platform.getId().toString()+"/";

        if (file != null) {
            objectKey = file.getOriginalFilename();
            fileName = file.getOriginalFilename();
            JSONObject jsonObject = JSON.parseObject(entity.getPayConfig());
            jsonObject.put("cert", folder + "/" + objectKey);
            entity.setPayConfig(JSONObject.toJSONString(jsonObject));
        }

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        if (file != null) {
            result = uploadService.fileUpload(bucketName, objectKey, fileName, folder, true, file);
            if (!result.isSuccess()) {
                throw new ServiceException("证书上传异常:" + result.getMsg());
            }
        }
        return Response.success("新增成功");
    }

    /**
     * @param entity
     * @param file
     * @return boolean
     * @author: Mr.wu
     * @descripton: 修改支付配置和支付证书
     * @date: 10:13 2019/6/10
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payment", allEntries = true)
    @Logable(authName = "支付服务-支付方式配置信息-更新支付方式配置信息并上传证书")
    @Override
    public Response updateByCert(Payment entity, MultipartFile file) {
        //验证平台属性
        Response result = platformService.getById(entity.getPlatformId());
        if (!result.isSuccess() || result.getData() == null) {
            return Response.failed("校验平台信息失败");
        }
        Platform platform = (Platform) result.getData();
        //TODO 根据租户或平台获得存储空间名称
        String bucketName = "obs-7d37";
        String objectKey = "";
        String fileName = "";
        String folder = platform.getId().toString() + "/";

        if (file != null) {
            objectKey = file.getOriginalFilename();
            fileName = file.getOriginalFilename();
            JSONObject jsonObject = JSON.parseObject(entity.getPayConfig());
            jsonObject.put("cert", folder + objectKey);
            entity.setPayConfig(JSONObject.toJSONString(jsonObject));
        }

        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        if (file != null) {
            result = uploadService.fileUpload(bucketName, objectKey, fileName, folder, true, file);
            if (!result.isSuccess()) {
                throw new ServiceException("证书上传异常:" + result.getMsg());
            }
        }
        return Response.success("修改成功");
    }

    /**
     * @param id
     * @return com.hoshiicloud.payment.Payment
     * @description: 根据id查询支付方式配置信息
     */
    @Override
    @Cacheable(cacheNames = "Payment", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "支付服务-支付方式配置信息 -查询支付方式配置信息 ")
    public Payment getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    @Logable(authName = "支付服务- -根据参数查询 ")
    @Cacheable(cacheNames = "Payment", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5('Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ',queryWrapper=' + #queryWrapper.toString() + ')')")
    public Payment getByParam(QueryWrapper queryWrapper) {
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * @param entity
     * @return boolean
     * @description: 新增支付方式配置信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payment", allEntries = true)
    @Logable(authName = "支付服务-支付方式配置信息-新增支付方式配置信息")
    public boolean save(Payment entity) {
        //ID为自增
        //entity.setCreatedtime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改支付方式配置信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payment", allEntries = true)
    @Logable(authName = "支付服务-支付方式配置信息管理-修改支付方式配置信息")
    public boolean updateById(Payment entity) {
        //entity.setUpdatedtime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param queryWrapper
     * @return IPage
     * @description: 分页查询支付方式配置信息
     */
    @Override
    @Logable(authName = "支付服务-支付方式配置信息管理-分页查询支付方式配置信息")
    @Cacheable(cacheNames = "Payment", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5('Page(current=' + #page.getCurrent() + ', size=' + #page.getSize() + '), Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ',queryWrapper=' + #queryWrapper.toString() + ')')")
    public IPage<Payment> page(IPage<Payment> page, Wrapper<Payment> queryWrapper) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payment", allEntries = true)
    @Logable(authName = "支付服务-支付方式配置信息管理-删除支付方式配置信息")
    public boolean deleteById(Payment entity) {
        //entity.setUpdatedtime(LocalDateTime.now());
        //entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }
}
